package fr.opensagres.xdocreport.samples.docxandvelocity.web.servlet;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import fr.opensagres.xdocreport.core.document.DocumentKind;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.web.dispatcher.AbstractXDocReportWEBController;
import fr.opensagres.xdocreport.samples.odtandvelocity.model.Developer;
import fr.opensagres.xdocreport.samples.odtandvelocity.model.Project;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;
import fr.opensagres.xdocreport.template.formatter.FieldsMetadata;

public class ListControler extends AbstractXDocReportWEBController{
	public static final String REPORT_ID = "ODTProjectWithVelocityList";

	public ListControler() {
		super(TemplateEngineKind.Velocity, DocumentKind.ODT);
	}

	public InputStream getSourceStream() {
		return HelloWorldControler.class
				.getResourceAsStream("ODTProjectWithVelocityList.odt");
	}
	
	@Override
	protected FieldsMetadata createFieldsMetadata() {		
		FieldsMetadata metadata = new FieldsMetadata();
        metadata.addFieldAsList("developers.Name");
        metadata.addFieldAsList("developers.LastName");
        metadata.addFieldAsList("developers.Mail");
        return metadata;
	}
	
	public void populateContext(IContext context, IXDocReport report,
			HttpServletRequest request) {
		String name = request.getParameter("name");
		String fname = request.getParameter("fname");
		String lname = request.getParameter("lname");
		String email = request.getParameter("email");
        Project project = new Project(name);
        context.put("project", project);

        int nbDevelopers = 0;
        try {
                nbDevelopers = Integer.parseInt(request
                                .getParameter("nbDevelopers"));
        } catch (Throwable e) {

        }
        List<Developer> developers = new ArrayList<Developer>(nbDevelopers);
        for (int i = 0; i < nbDevelopers; i++) {
                developers
                                .add(new Developer(fname + i, lname + i, email + i));
        }
        context.put("developers", developers);
	}
}
